<?php
$appid='你的appid';
$secret='你的app_secret';

class wxjssdk {
	//检查

	static function check() {

		if (!function_exists('C'))
			exit('不存在thinkPHP::C函数，请修改本类中使用C函数的地方');
		if (!C('AccountAppID'))
			exit('请配置：AccountAppID，公众号appid');
		if (!C('AccountAppSecret'))
			exit('请配置：AccountAppSecret，公众号secret');
	}

    public static $appid;
    public static $secret;

	static function load($appid,$secret) {
        if(!$appid || !$secret){
            exit('必须传入：公众号appid、secret');
        }
        self::appid = $appid;
        self::secret=$secret;



		//self::check();
		$jsapi_ticket = self::getJsapi_ticket();
		$nonceStr = randstr(16);
		//随机字符串

		$timestamp = time();

		//时间戳

		$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

		$signature = self::getSignature($jsapi_ticket, $nonceStr, $timestamp, $url);

		$jssdk = array("jsapi_ticket" => $jsapi_ticket, "url" => $url, 'appid' =>$appid, "str" => $nonceStr, "time" => $timestamp, "sign" => $signature);
		/*
        $jssdk_html = dirname(__FILE__) . '/wx_jssdk.html';
		if (file_exists($jssdk_html))
			require_once ($jssdk_html);*/
		return $jssdk;
		//echo json_encode($result);

	}



	static function getSignature($jsapi_ticket, $noncestr, $timestamp, $url) {
		$string1 = "jsapi_ticket=" . $jsapi_ticket . "&noncestr=" . $noncestr . "&timestamp=" . $timestamp . "&url=" . $url;
		$sha1 = sha1($string1);
		return $sha1;
	}

	static function getJsapi_ticket() {
		$cache = new Cache();
		$cache = new Cache(7000, 'cache/');
		//需要创建cache文件夹存储缓存文件。

		//从缓存从读取键值 $key 的数据

		$jsapi_ticket = $cache -> get("jsapi_ticket");

		$access_token = self::getAccess_token();
		//如果没有缓存数据

		if ($jsapi_ticket == false) {

			$access_token = self::getAccess_token();
			$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
			$data = array('type' => 'jsapi', 'access_token' => $access_token);
			$header = array();
			$response = json_decode(self::curl_https($url, $data, $header, 5));
			$jsapi_ticket = $response -> ticket;
			//写入键值 $key 的数据

			$cache -> put("jsapi_ticket", $jsapi_ticket);

		}
		return $jsapi_ticket;
	}

	static function getAccess_token($APPID = 0, $SECRET = 0) {
		$cache = new Cache();
		$cache = new Cache(7000, 'cache/');
		//从缓存从读取键值 $key 的数据

		$access_token = $cache -> get("access_token");



		//如果没有缓存数据

		if ($access_token == false) {

			$url = 'https://api.weixin.qq.com/cgi-bin/token';
			$data = array('grant_type' => 'client_credential', 'appid' => self::appid, 'secret' => self::secret);
			$header = array();

			$response = json_decode(self::curl_https($url, $data, $header, 5));
			$access_token = $response -> access_token;
			//写入键值 $key 的数据

			$cache -> put("access_token", $access_token);

		}
		return $access_token;
	}

	/** curl 获取 https 请求

	 * @param String $url 请求的url

	 * @param Array $data 要發送的數據

	 * @param Array $header 请求时发送的header

	 * @param int $timeout 超时时间，默认30s

	 */
	static function curl_https($url, $data = array(), $header = array(), $timeout = 30) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		// 跳过证书检查

		curl_setopt($ch, CURLOPT_URL, $url);

		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

		$response = curl_exec($ch);

		if ($error = curl_error($ch)) {
			die($error);
		}

		curl_close($ch);

		return $response;

	}

}

class Cache {
	private $cache_path;
	//path for the cache

	private $cache_expire;

	//seconds that the cache expires



	//cache constructor, optional expiring time and cache path

	public function Cache($exp_time = 3600, $path = "cache/") {

		$this -> cache_expire = $exp_time;
		$this -> cache_path = $path;
	}

	//returns the filename for the cache

	private function fileName($key) {

		return $this -> cache_path . md5($key);
	}

	//creates new cache files with the given data, $key== name of the cache, data the info/values to store

	public function put($key, $data) {

		$values = serialize($data);
		$filename = $this -> fileName($key);
		$file = fopen($filename, 'w');
		if ($file) {//able to create the file
			fwrite($file, $values);
			fclose($file);
		} else
			return false;
	}

	//returns cache for the given key

	public function get($key) {

		$filename = $this -> fileName($key);
		if (!file_exists($filename) || !is_readable($filename)) {//can't read the cache
			return false;
		}
		if (time() < (filemtime($filename) + $this -> cache_expire)) {//cache for the key not expired
			$file = fopen($filename, "r");
			// read data file

			if ($file) {//able to open the file

				$data = fread($file, filesize($filename));

				fclose($file);
				return unserialize($data);
				//return the values

			} else

				return false;
		} else
			return false;
		//was expired you need to create new

	}



}
?>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<?php $jssdk = wxjssdk::load($appid,$secret);?>
<script>
	/*

	 * 注意：

	 * 1. 所有的JS接口只能在公众号绑定的域名下调用，公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

	 * 2. 如果发现在 Android 不能分享自定义内容，请到官网下载最新的包覆盖安装，Android 自定义分享接口需升级至 6.0.2.58 版本及以上。

	 * 3. 常见问题及完整 JS-SDK 文档地址：http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html

	 *

	 * 开发中遇到问题详见文档“附录5-常见错误及解决办法”解决，如仍未能解决可通过以下渠道反馈：

	 * 邮箱地址：weixin-open@qq.com

	 * 邮件主题：【微信JS-SDK反馈】具体问题

	 * 邮件内容说明：用简明的语言描述问题所在，并交代清楚遇到该问题的场景，可附上截屏图片，微信团队会尽快处理你的反馈。

	 */
	wx.config({
		debug: false,
		appId: "<?php echo $jssdk['appid'] ?>",
		timestamp: <?php echo $jssdk['time'] ?>,
		nonceStr: "<?php echo $jssdk['str'] ?>",
		signature: "<?php echo $jssdk['sign'] ?>",
		jsApiList: [
			'checkJsApi',
			'onMenuShareTimeline',
			'onMenuShareAppMessage',
			'onMenuShareQQ',
			'onMenuShareWeibo',
			'onMenuShareQZone',
			'hideMenuItems',
			'showMenuItems',
			'hideAllNonBaseMenuItem',
			'showAllNonBaseMenuItem',
			'translateVoice',
			'startRecord',
			'stopRecord',
			'onVoiceRecordEnd',
			'playVoice',
			'onVoicePlayEnd',
			'pauseVoice',
			'stopVoice',
			'uploadVoice',
			'downloadVoice',
			'chooseImage',
			'previewImage',
			'uploadImage',
			'downloadImage',
			'getNetworkType',
			'openLocation',
			'getLocation',
			'hideOptionMenu',
			'showOptionMenu',
			'closeWindow',
			'scanQRCode',
			'chooseWXPay',
			'openProductSpecificView',
			'addCard',
			'chooseCard',
			'openCard'
		]
	});
</script>
<script src="http://203.195.235.76/jssdk/js/zepto.min.js"></script>


<script>
	wx.ready(function(){
	    var shareData = {
		    title: $('title').text().replace(/[\s\t\v\f\b\r\n ]/,'').replace(' ',''), //分享的标题
			desc: "分享的描述", //分享的描述
			link: window.location.href,//link，只能是本站地址
			imgUrl: 'http://xxxxx/xxx.jpg' //分享所带的图片地址，需要带http://.....
		};
		wx.onMenuShareAppMessage(shareData);
		wx.onMenuShareTimeline(shareData);
	});
</script>

